
package juc.base;

import java.util.concurrent.TimeUnit;
/*正确的关闭线程；不能使用stop（）方法
* 有可能无法正常释放资源
* 使用两阶段中断来保证线程正常 结束并释放资源
* */
public class TwoPhaseStop {
    /*守护线程*/
    static volatile boolean tag = false;

    public static void main(String[] args) throws Exception {

        Thread t1 = new Thread(() -> {
            while (!tag) {
                try {
                    System.out.println("t1 start");
                    TimeUnit.SECONDS.sleep(4);
                    System.out.println("t1 end");
                } catch (InterruptedException e) {
                    /*抛出异常配合finally使用释放资源*/
//                    throw new RuntimeException(e);
                    /*错误打印配合flag使用*/
                    e.printStackTrace();
                }
//                finally {
//                    System.out.println("release resource");
//                }
            }
            flag:
            System.out.println("release resource");
        });
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        tag = true;
        t1.interrupt();

        TimeUnit.SECONDS.sleep(5);

    }
}